<template>
  <div class="MainSlotBox">
    <div class="shadow" v-if="timeNum > 0">
      数据同步中，剩余{{ minutes }}分钟
    </div>
    <MainSlot>
      <template v-slot:searchForm>
        <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" :key="updateKey"
          @search="search" @isUnfold="(v) => {
      unfoldFlag = v;
    }
      ">
        </SearchForm>
      </template>
      <template v-slot:btn>
        <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
      </template>
      <template v-slot:table>
        <el-table v-show="timeNum <= 0" :data="tableData" border ref="tabRef" height="100%" v-loading="loading">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column align="center" prop="dbilldate" label="月份"></el-table-column>
          <!-- <el-table-column align="center" prop="fun" label="场部+功能">
            <template slot-scope="scope">
              <span>{{ scope.row.department + scope.row.functions }}</span>
            </template>
</el-table-column>
<el-table-column align="center" prop="department" label="场部名称"></el-table-column> -->
          <el-table-column align="center" prop="cdptname" label="塘号" width="160"></el-table-column>
          <el-table-column align="center" prop="area" label="面积亩"></el-table-column>
          <el-table-column align="center" prop="fishstarting" label="入鱼开始"></el-table-column>
          <el-table-column align="center" prop="fishend" label="出鱼结束"></el-table-column>
          <el-table-column align="center" prop="days" label="养殖天数"></el-table-column>
          <el-table-column align="center" prop="cmaterialvname" label="品种"></el-table-column>
          <el-table-column align="center" label="入鱼">
            <el-table-column align="center" prop="intakenum" label="入鱼数量" width="110"></el-table-column>
            <el-table-column align="center" prop="intakeaveweight" label="均重" width="110"></el-table-column>
            <!-- <el-table-column align="center" prop="intakeqty" label="入鱼条数" width="110"></el-table-column> -->
          </el-table-column>
          <el-table-column align="center" label="出鱼">
            <el-table-column align="center" prop="producenum" label="出鱼数" width="110"></el-table-column>
            <!-- <el-table-column align="center" prop="produceaveweight" label="总出鱼条数" width="110"></el-table-column> -->
            <el-table-column align="center" prop="produceqty" label="均重" width="110"></el-table-column>
          </el-table-column>
          <el-table-column align="center" prop="zzl" label="增总量"></el-table-column>
          <el-table-column align="center" prop="rlb" label="肉料比"></el-table-column>
        </el-table>
      </template>
      <template v-slot:pagination>
        <!-- <Pagination @current-change="handleCurrentChange" :page="page" :total="total">
        </Pagination> -->
        <el-pagination @size-change="(e) => { handleSizeChange(e), customSize = e }"
          @current-change="handleCurrentChange" :current-page="page"
          :page-sizes="[10, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, customSize]" :page-size="pageSize"
          layout="total,slot, sizes, prev, pager, next, jumper" background :total="total">
          <template #default>
            <el-input type="number" style="width: 150px;" v-model="customSize" placeholder="请输入内容" @change="() => {
      customSize = customSize < 1 ? customSize = 1 : Math.floor(customSize)
      handleSizeChange(customSize);
    }"><template slot="append">条/页</template></el-input>
          </template>
        </el-pagination>
      </template>
      <template v-slot:dialogModule>
        <waterAddEdit v-model="addEditShow" :stordocList="stordocList" @close="closeDia" @reflash="getTableList" />
        <waterImport v-model="importShow" @close="closeDia" @reflash="getTableList" />
      </template>
    </MainSlot>
  </div>
</template>
<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from "@/components-production-management/Pagination";
import BtnSlot from "@/components-production-management/BtnSlot";
import waterAddEdit from "./components/waterAddEdit";
import waterImport from "./components/waterImport";
import ncBasicInfoApi from "@/api/nc-basic-info/index";
import ncClearPondApi from "@/api/module/ncClearPond";
import TableData from "@/components-production-management/TableData";
import SearchForm from "@/components-production-management/SearchForm";
import baseUrl from "@/api/baseURL";
import { mymixin } from "@/utils/mixin";
export default {
  mixins: [mymixin],
  components: {
    MainSlot,
    Pagination,
    BtnSlot,
    waterAddEdit,
    TableData,
    SearchForm,
    waterImport,
  },
  data() {
    return {
      timeNum: -1,
      minutes: '00:00',
      formItemList: [
        {
          label: "塘号",
          type: "select",
          selectOptions: [],
          param: "ncWarehouseidLists",
          defaultSelect: "", // 下拉框默认选中项
          multiple: true,
          isShow: true,
          collapseTags: true,
        },
        {
          label: "日期查询",
          type: "daterange",
          defaultSelect: [],
          param: "dateTime",
          isShow: true,
        },
      ],
      unfoldFlag: false,
      btnList: ["export", "sync"],
      addEditShow: false,
      tableData: [],
      loading: false,
      page: 1,
      total: 0,
      pageSize: 100,
      customSize: 100,
      stordocList: [],
      updateKey: 0,
      filterData: {},
      importShow: false,
      time: null
    };
  },
  created() {
    this.queryStordoc();
  },
  mounted() {
    this.getTimeNum()
  },
  beforeDestroy() {
    clearInterval(this.time)
  },
  methods: {
    getTimeNum() {
      let syncTime = new Date(sessionStorage.syncTime || '')
      let nowTime = new Date()
      var timestamp1 = syncTime.getTime();
      var timestamp2 = nowTime.getTime();
      this.timeNum = 15 * 60 - ((timestamp2 - timestamp1) / 1000).toFixed(0)
      this.timeNum = this.timeNum || -1
      console.log('this.timeNum', this.timeNum)
      if (this.timeNum > 0) {
        this.timeNumSetInterval()
      } else {
        this.getTableList();
      }
    },
    timeNumSetInterval() {
      let that = this
      this.time = setInterval(() => {
        this.timeNum--
        if (this.timeNum <= 0) {
          this.getTableList();
          clearInterval(that.time);
          this.timeNum = -1;
        }
        this.minutes = this.formatSeconds(this.timeNum)
      }, 999)
    },
    formatSeconds(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
    },
    search(data) {
      this.filterData = JSON.parse(JSON.stringify(data));
      this.page = 1;
      this.getTableList();
    },
    getTableList() {
      const { page, pageSize, filterData } = this;
      const paylod = {
        page,
        size: pageSize,
      };
      const entity = JSON.parse(JSON.stringify(filterData));
      if (entity.dateTime && entity.dateTime.length > 0) {
        entity.startTime = filterData.dateTime[0] + " 00:00:00";
        entity.endTime = filterData.dateTime[1] + " 23:59:59";
        delete entity.dateTime;
      }
      if (filterData.ncWarehouseidLists) {
        entity.ncWarehouseidLists = filterData.ncWarehouseidLists.toString();
      }
      paylod.entity = entity;
      this.loading = true;
      ncClearPondApi
        .queryPageQtjl(paylod)
        .then((res) => {
          if (res.success) {
            const { data } = res;
            this.tableData = data.content;
            this.total = data.totalElements;
            if (res.data.content.length === 0 && this.page !== 1) {
              this.page--;
              this.getTableList();
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    queryStordoc() {
      ncBasicInfoApi.queryQtjlFishPond({}).then((res) => {
        this.stordocList = res.data;
        this.formItemList[0].selectOptions = this.stordocList.map((data) => {
          return {
            text: data,
            value: data,
          };
        });
        this.updateKey++;
      });
    },
    getBtnEvent(v) {
      if (v == 'sync') {
        console.log(v)
        this.syncData()
      } else if (v == 'export') {
        this["btn" + this.capitalizeFirstLetter(v)]();
      }
    },
    syncData() {
      this.$confirm('此操作将会主动同步nss数据,大约需要15分钟,您是否继续操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', baseUrl.webServiceUrl + 'base/ncClearPond/synByHand', true);
        xhr.setRequestHeader("Token", sessionStorage.token)
        xhr.setRequestHeader("Homebaseid", sessionStorage.homeBaseId)
        xhr.send();
        sessionStorage.setItem('syncTime', new Date())
        setTimeout(() => {
          this.getTimeNum();
          xhr.abort();
        }, 1000)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    btnAdd() {
      this.addEditShow = true;
    },
    btnExport() {
      const { filterData } = this;
      const entity = JSON.parse(JSON.stringify(filterData));
      if (entity.dateTime && entity.dateTime.length > 0) {
        entity.startTime = filterData.dateTime[0] + " 00:00:00";
        entity.endTime = filterData.dateTime[1] + " 23:59:59";
        delete entity.dateTime;
      }
      if (filterData.ncWarehouseidLists) {
        entity.ncWarehouseidLists = filterData.ncWarehouseidLists.toString();
      }
      ncClearPondApi.exportQtjl({
        page: this.page,
        size: this.pageSize,
        entity: { ...entity }
      }).then((res) => {
        this.getFileNameAndDownload(res);
      });
    },
    btnImport() {
      this.importShow = true;
    },
    capitalizeFirstLetter(str) {
      if (!str) return "";

      // 将字符串的第一个字符转换为大写，剩余的字符保持不变
      return str.charAt(0).toUpperCase() + str.slice(1);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getTableList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getTableList();
    },
    closeDia() {
      this.addEditShow = false;
      this.importShow = false;
      this.getTableList();
    },
  },
};
</script>
<style lang="scss" scoped>
.MainSlotBox {
  width: 100%;
  height: 100%;
  position: relative;

  .shadow {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #ffffff99;
    z-index: 9999;
    display: flex;
    justify-content: space-around;
    align-items: center;
    font-size: 24px;
    cursor: pointer;
  }
}
</style>
